﻿using Newtonsoft.Json;
using TenantSecurityProvider.Models;

namespace TenantSecurityProvider.Utils;

public abstract class UserServiceRequestUtils
{
    private const string ApiPrefix = "http://localhost:22345/UserService/UserService/";

    private static Task<T> PostAsync<T>(string route, object content = null)
    {
        return HttpUtils.PostAsync<T>(ApiPrefix + route, content == null ? null : JsonConvert.SerializeObject(content));
    }

    private static async Task<RsaResult> GetRsaPublicKeyAsync()
    {
        var response = await PostAsync<RsaResponse>("GetRSAPublicKey");

        return response.Result;
    }

    public static Task<UserInfo> GetUserInfoAsync(string userName)
    {
        return PostAsync<UserInfo>("GetUserInfo", new
        {
            UserName = userName,
        });
    }

    public static Task<List<UserServiceUser>> GetAllUsersAsync()
    {
        return PostAsync<List<UserServiceUser>>("GetAllUsers");
    }

    public static Task<Dictionary<string, string>> GetAllRolesAsync()
    {
        return PostAsync<Dictionary<string, string>>("GetAllRoles");
    }

    public static Task<List<OrganizationNodeInfo>> GetAllOrganizationNodeInfosAsync()
    {
        return PostAsync<List<OrganizationNodeInfo>>("GetAllOrganizationNodeInfos");
    }

    public static async Task<Dictionary<int, List<OrganizationMemberInfo>>> GetOrganizationMemberDicAsync()
    {
        var result = await PostAsync<OrganizationMemberDicResult>("GetOrganizationMemberDic", new ());
        return result.OrganizationMemberDic;
    }

    public static async Task<bool> ValidateUser(string userName, string password)
    {
        var rsa = await GetRsaPublicKeyAsync();

        var encryptedPassword = RsaDecryptUtils.Encrypt(password, rsa.Value);

        var content = new
        {
            userName,
            password = encryptedPassword,
            keyId = rsa.Id,
            isSecurityProvider = false,
        };

        var result = await PostAsync<LoginResponse>("ValidateUser", content);

        return result.Result;
    }
}
